<?php defined('SYSPATH') OR die('No direct access allowed.');

/**
 * 后台入口
 *
 * @author 陈蕾
 */

class Controller_Admin_Panel extends Controller_Template
{
	protected $_auto = false;

    public function before()
    {
        $this->template = '';
        if ($this->request->action != 'logout') {
            $this->template = "admin/panel/{$this->request->action}";
            parent::before();
        }
    }

    // 管理首页
    public function action_index()
    {
        // 未登录则跳转至登录页
        if ( ! Auth::has_logged_in()) {
            $this->request->redirect('admin/login');
        }
    }

    // 登录页
    public function action_login()
    {
        if ($_POST) {
        	$captcha  = Arr::get($_POST, 'captcha');
            $username = Arr::get($_POST, 'username');
            $password = Arr::get($_POST, 'password');

        	if ( ! Captcha::valid($captcha)) {
				$this->error('验证码错误，登录失败！');
        	}

            $post = array(
                'a_name' => $username,
                'a_password' => $password
            );
            $post = Validate::factory($post)
                ->filter(TRUE, 'trim')
                ->rule('a_name', 'not_empty')
                ->rule('a_password', 'not_empty');

            if ( ! $post->check()) {
                $errors = $post->errors('admin');
                $this->error(array_shift($errors));
            }

            if (Auth::do_login($username, $password)) {
                $this->request->redirect('admin');
            } else {
                $this->error('登录失败，用户名或密码错误！');
            }
        } else {
            if (Auth::has_logged_in()) {
                $this->request->redirect('admin');
            }
        }
    }

    // 退出登录
    public function action_logout()
    {
        if (Auth::do_logout()) {
            $this->request->redirect(URL::site('admin/login'));
        }
    }

    // 错误信息
    public function error($error)
    {
        $this->request->redirect('admin/login?error=' . urlencode($error));
    }
}